Lesson 4 - Creating if statements

If statements allow code to be run depending on if certain requirements have been met. The conditional expression is the most important part of a if statement. When a condition is evaluated either the true or false block will be run, never both. This can be shown in the diagram below.

This can be represented by the python code below.


if a < b:
	print a
else:
	print b
				

It is important to understand if statements in this way as they help in their creation. Getting conditions wrong is one of the biggest source of bugs in code so it is worth getting them right. Especially when code gets more complex. Imagine a scenario where a student is deciding on doing a retake. If the mark they got is less than 50 then they will do a retake otherwise they will not.

However the student does not want to over burden themselves so they decide not to take too many retakes. This new scenario can be shown in the diagram and code below.


if mark < 50:
	if exam < 4:
		print "do retake"
	else print "do not do retake"
else:
	print "do not do retake"
				

Creating the truth tree diagram leads directly onto creating a if statement in python. On top of that it is easy to build up a overall idea of how the code will work by showing all possibilities. Notice that the else of the top most if statement does not have a nested if. This is shown on the diagram very clearly.

Consider the example of finding the biggest of three values. max(a,b,c). The basic idea is to compare two items together and then compare the biggest against the third to find the overall biggest. This can stump students as they find it difficult to manage all of the different possibilities. The truth tree diagram helps here!


# there is a way of creating min with a variable number of arguments
# but the point of this is looking at if statements!
def min(a,b,c):
	if a>b:
		if a>c: return a
		else: return c
	else:
		if b>c: return b
		else: return c